using Joy.Erp.BasicArchives.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace Joy.Erp.BasicArchives.ItemMasters
{
    public class BomComponentModelConfiguration : IModelConfiguration
    {
        public void Build(ModelBuilder builder)
        {
            builder.Entity<BomComponent>(b =>
            {
                b.ToTable(BasicArchivesDbProperties.DbTablePrefix + nameof(BomComponent), BasicArchivesDbProperties.DbSchema);
                b.ConfigureByConvention();
                b.ConfigureDocumentLineAggregateRoot();

                b.Property(x => x.ItemMasterId).IsRequired();
                b.Property(x => x.ItemCode).IsRequired(BomComponentConsts.ItemCodeRequired);
                b.Property(x => x.ItemCode).HasMaxLength(BomComponentConsts.ItemCodeMaxLength);
                b.Property(x => x.ItemName).HasMaxLength(BomComponentConsts.ItemNameMaxLength);
                b.Property(x => x.ItemSpec).HasMaxLength(BomComponentConsts.ItemSpecMaxLength);
                b.Property(x => x.UseCount).HasColumnType(BomComponentConsts.UseCountColumnType);
                b.Property(x => x.ParentCount).HasColumnType(BomComponentConsts.ParentCountColumnType);
                b.Property(x => x.UnitId).IsRequired();

                b.HasOne(x => x.ItemMaster).WithMany().HasForeignKey(x => x.ItemMasterId).OnDelete(DeleteBehavior.Restrict);
                b.HasOne(x => x.Unit).WithMany().HasForeignKey(x => x.UnitId).OnDelete(DeleteBehavior.Restrict);
            });
        }

        public void Entity(IAbpDbContextRegistrationOptionsBuilder options)
        {
            options.Entity<BomComponent>(opt =>
            {
                opt.DefaultWithDetailsFunc = query =>
                {
                    return query
                        .Include(x => x.Document)
                            .ThenInclude(x => x.ItemMaster)
                        .Include(x => x.Document)
                            .ThenInclude(x => x.Unit)
                        .Include(x => x.ItemMaster)
                        .Include(x => x.Unit)
                            .ThenInclude(x => x.Unit)
                        ;
                };
            });
        }
    }
}